package com.astro.common.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.astro.app.AppConfig;
import com.astro.app.AppContext;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

public class PDFGenerator {

	public static void generatePdfFile(String fileContentPath, String outputPath) {
		// create a new document
		Document document = new Document();
		try {
			System.out.println("Generating PDF file...");
			// create a pdfwriter instance
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
			// open the document
			document.setPageSize(PageSize.A4.rotate());
			document.setMargins(15,10,10,10);
			document.open();

			HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
			htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
			htmlContext.setImageProvider(new AbstractImageProvider() {
				public String getImageRootPath() {
					AppConfig appConfig = (AppConfig) AppContext.getSpringContext().getBean(AppConfig.class);
					return  appConfig.getTemplatePath();
				}
			});

			CSSResolver cssResolver = XMLWorkerHelper.getInstance()
					.getDefaultCssResolver(true);

			Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
					new HtmlPipeline(htmlContext, new PdfWriterPipeline(
							document, writer)));
			XMLWorker worker = new XMLWorker(pipeline, true);
			XMLParser p = new XMLParser(worker);
			p.parse(new FileInputStream(fileContentPath));
			System.out.println("Finished generating PDF!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			document.close();	
		}
	}
}
